/**
 * @name Global request setting
 * @author can
 * @time 2019年7月5日22点03分
 */

import http from './request'

// baseUrl
http.config.baseURL = "https://rsgl.cyygg.cn/api/"
//http.config.baseURL = "http://localhost/api/"

let num = 0;

// 请求拦截器
http.interceptor.request = (config) => {

	if (num == 0) {
		// 开启请求弹框
		uni.showLoading({
			title: '请求中...',
			mask: true
		})
	}
	num++;

	const token = uni.storage.get("token")
	if (token) {
		config.header = {
			Authorization: `Bearer ${token}`,
		}
	} else {
		// #ifdef H5
		if (config.login) {
			uni.navigateTo({
				url: "/pages/login/login"
			})
		}
		// #endif
	}
}

// 响应拦截器
http.interceptor.response = (response) => {
	num--;


	// 使用setTimeout确保在下一个事件循环中执行hideLoading
	setTimeout(() => {
		if (num == 0) {
			// 隐藏请求弹框
			uni.hideLoading();
		}
	}, 0)

	if (response.statusCode == 401) {
		uni.removeStorageSync('token');
		var redirectUrl;
		// #ifdef H5
		redirectUrl = window.location.href.split("#")[1];
		//#endif

		// #ifndef H5
		redirectUrl = getCurrentPages()[0].fullPath;
		// #endif
		uni.storage.set("login_refer", redirectUrl);
		uni.router.redirectTo('/hyb_o2o/login/login');
		return response;
	} else if (response.statusCode == 500) {
		setTimeout(() => {
			uni.showToast({
				icon: "none",
				title: response.data.message
			})
		}, 500)
		return response;
	} else if (response.statusCode == 200 || response.statusCode == 201) {
		return response
	} else {
		setTimeout(() => {
			uni.showToast({
				icon: "none",
				title: response.data
			})
		}, 500)
		return null;
	}
}

export default {
	get(url, data) {
		if (!data) data = {};
		data["uniacid"] = uni.getStorageSync("uniacid");
		return http.request({
			url: url,
			method: 'GET',
			data,
		})
	},
	post(url, data) {
		if (!data) data = {};
		data["uniacid"] = uni.getStorageSync("uniacid");
		return http.request({
			url: url,
			method: 'POST',
			data,
		})
	}
}